package com.ow.dva.module.base.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.ow.dva.module.base.service.ImageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class ImageServiceImpl implements ImageService {

    @Value("${dva.static-path}")
    private String staticPath;

    /**
     *
     * @param relativeDir 相对路径
     * @return
     */
    @Override
    public String getStaticPath(String relativeDir) {
        // 配置路径
//        if(staticPath.equals("auto")){
            try {
                staticPath = FileUtil.file(".", relativeDir).getCanonicalPath();
                return staticPath;
            } catch (IOException e) {
                e.printStackTrace();
                return staticPath ;
            }
//        }
//        return staticPath ;
    }

    @Override
    public String createDateDir(String dir) {
        //验证文件夹，如果文件夹不存在则创建
        File file = new File( dir);
        if  (!file .exists()  && !file .isDirectory()) {
            boolean isMk = file .mkdirs();
        }
        return dir;
    }

    @Override
    public String imageFileUpload(MultipartFile imageFile) throws IOException {
        //获取图片文件类型
        String contentType = imageFile.getContentType();
        //获取保存目录
        String staticPath = getStaticPath("/upload");
        // 获取文件相对路径以及要保存的文件名
        String relativePath = generateImageFileName(staticPath,contentType);
        //保存文件到绝对路径
        imageFile.transferTo(new File(staticPath + relativePath));
        return relativePath;
    }

    /**
     * 生成日期路径
     * @param staticPath
     * @return
     */
    public String generateTodayDir(String staticPath){
        // 日期路径
        String dateDir = new SimpleDateFormat("yyyyMMdd").format(new Date());
        createDateDir(staticPath + "/" + dateDir );
        return "/" + dateDir;
    }

    /**
     * 获取文件路径并创建日期文件夹
     * @param staticPath 绝对路径
     * @param contentType 文件类型
     * @return 文件相对路径
     */
    public String generateImageFileName(String staticPath,String contentType) {
        String todayDir = generateTodayDir(staticPath);
        String filename = null;
        //生成随机ID
        String simpleUUID = IdUtil.simpleUUID();
        switch (contentType){
            case "image/jpeg"    : filename = simpleUUID + ".jpg";       break;
            case "image/png"     : filename = simpleUUID + ".png";      break;
            case "image/gif"        : filename = simpleUUID + ".gif";         break;
            case "image/bmp"   : filename = simpleUUID + ".bmp";     break;
            default                            : filename = simpleUUID + ".jpg";
        }
        return todayDir + "/" + filename;
    }

    @Override
    public String uploadPassPic(MultipartFile file, String path) throws IOException{
        //获取图片文件类型
        String contentType = file.getContentType();
        //获取保存目录
        String staticPath = getStaticPath("/upload");
        generateTodayDir(staticPath);
        // 获取文件相对路径以及要保存的文件名

        //保存文件到绝对路径
        file.transferTo(new File(staticPath + path));
        return path;
    }

    @Override
    public void downFile(HttpServletResponse response, String realPath) throws IOException {
        if(!"".equals(realPath)){
            File file  = new File(realPath);
            if(file.exists()){
                outputStream(response,file,file.getName());
            }
        }
    }

    private void outputStream(HttpServletResponse response, File file,String fileName) throws IOException {
        InputStream in = new FileInputStream(file);
        //response.setContentType("image/jpeg");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.addHeader("Content-Length", "" + file.length());
        OutputStream os = response.getOutputStream();
        byte[] b = new byte[1024];
        while( in.read(b)!= -1){
            os.write(b);
        }
        in.close();
        os.flush();
        os.close();
    }
}
